import os

import setting
from database.mydatabase import SqliteDataBase
from drivers.driver import get_driver
from models.book import BookInfo, load_book_info_by_book_name
from spider.platform import sync
from spider.resources import douban
from spider.storage import ctfile
from spider.storage.ctfile import CTFile


def list_book(path, category_list: list = []):
    if os.path.isfile(path):
        return
    books = os.listdir(path)
    i = 1
    book_dict = {}
    for book in books:
        print(i, book)
        book_dict[str(i)] = book
        i += 1
    book_num = input('请输入对应序号: ')
    book_name: str = book_dict[book_num]
    book_path = path + '/' + book_name
    if os.path.isdir(book_path):
        category_list.append(book_name)
        return list_book(book_path, category_list)
    return [category_list, book_name]


if __name__ == '__main__':
    category_list, book_name = list_book(setting.BOOK_PATH)
    database = SqliteDataBase()
    book_info = load_book_info_by_book_name(database, book_name)
    if book_info is None:
        book_title = ''.join(book_name.split('.')[:-1])
        book_info = douban.get_book(book_title)
        book_info.book_name = book_name
        insert_book_sql = book_info.get_insert_book_sql()
        database.sql_execute(insert_book_sql)
    book_info.categorys = '##'.join(category_list)
    driver = get_driver()
    if book_info.download_url is None:
        ctfile = CTFile(driver)
        download_url = ctfile.get_download_url(book_info)
        book_info.download_url = download_url
    sync.sync_article(driver, book_info)
    update_book_sql = book_info.get_update_book_sql()
    database.sql_execute(update_book_sql)
    print(book_info.generate_markdown_article())

    database.close()
